package com.rayson.yututu.controller;

import cn.hutool.core.io.IoUtil;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.utils.IOUtils;
import com.rayson.yututu.annotation.AuthCheck;
import com.rayson.yututu.common.BaseResponse;
import com.rayson.yututu.constant.UserConstant;
import com.rayson.yututu.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author: rayson
 * Description:
 * Version: 1.0
 * Date: 2024-12-24 21:00
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    @PostMapping("/upload")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<String> uploadToCos(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String key = "/test/" + originalFilename;
        try {
            cosManager.putObject(key, file.getInputStream(), new ObjectMetadata());
            return BaseResponse.success(key);
        } catch (IOException e) {
            log.error("上传文件失败", e);
            return BaseResponse.fail("上传文件失败");
        }
    }

    @GetMapping("/download")
    public void downloadFromCos(String filePath, HttpServletResponse response) {
        COSObjectInputStream objectContent = null;
        try {
            COSObject cosObject = cosManager.getObject(filePath);
            objectContent = cosObject.getObjectContent();
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filePath);
            byte[] byteArray = IOUtils.toByteArray(objectContent);
            // 写入响应
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(byteArray);
            outputStream.flush();
        } catch (IOException e) {
            log.error("下载文件失败", e);
        } finally {
            IoUtil.close(objectContent);
        }
    }
}
